package com.googlecode.garbagecan.springsecuritystudy.acl;

import org.springframework.security.acls.*;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.objectidentity.ObjectIdentityImpl;
import org.springframework.security.acls.sid.PrincipalSid;

public class PermissionServiceImpl implements PermissionService {
	private MutableAclService mutableAclService;

	public void setMutableAclService(MutableAclService mutableAclService) {
		this.mutableAclService = mutableAclService;
	}

	public void addPermission(long id, String clz, String recipient, int mask) {
		PrincipalSid sid = new PrincipalSid(recipient);
		Permission permission = BasePermission.buildFromMask(mask);

		ObjectIdentity oid = null;

		if (clz.equals("account")) {
			oid = new ObjectIdentityImpl(Account.class, id);
		} else if (clz.equals("contract")) {
			oid = new ObjectIdentityImpl(Contract.class, id);
		}

		MutableAcl acl;
		try {
			acl = (MutableAcl) mutableAclService.readAclById(oid);
		} catch (NotFoundException nfe) {
			acl = mutableAclService.createAcl(oid);
		}

		acl.insertAce(acl.getEntries().length, permission, sid, true);
		mutableAclService.updateAcl(acl);
	}

	public void deletePermission(long id, String clz, String recipient, int mask) {
		PrincipalSid sid = new PrincipalSid(recipient);
		Permission permission = BasePermission.buildFromMask(mask);

		ObjectIdentity oid = null;
		if (clz.equals("account")) {
			oid = new ObjectIdentityImpl(Account.class, id);
		} else if (clz.equals("contract")) {
			oid = new ObjectIdentityImpl(Contract.class, id);
		}

		MutableAcl acl = (MutableAcl) mutableAclService.readAclById(oid);
		AccessControlEntry[] entries = acl.getEntries();

		for (int i = 0; i < entries.length; i++) {
			if (entries[i].getSid().equals(sid) && entries[i].getPermission().equals(permission)) {
				acl.deleteAce(i);
			}
		}
		mutableAclService.updateAcl(acl);
	}
}
